import { createAction } from 'redux-actions';
import * as types from '../constants/ActionTypes';
import * as Api from '../utils/WebAPIUtils.js';
import Tool from '../utils/ToolUtils.js';
// 渠道管理、发布至此渠道
// ========================

const getChannelAction = createAction(types.FETCH_OFFICIAL_CHANNEL, data => data);
const newChannelAction = createAction(types.NEW_OFFICIAL_CHANNEL, data => data);
const getOneChannelAction = createAction(types.FETCH_ONE_OFFICIAL_CHANNEL, data => data);
// const editChannelAction = createAction(types.EDIT_OFFICIAL_CHANNEL, data => data);
const saveMsg = createAction(types.SAVE_CHANNEL_ERROR_MSG, data => data);
const getPushCategoryAction = exports.getPushCategoryAction = createAction(types.FETCH_TEST_CATEGORY, data => data);
exports.resetSaveMsg = createAction(types.RESET_SAVE_ERROR_MSG, data => data);
exports.restoreChannel = createAction(types.RESTORE_CHANNEL, data => data);
exports.storageChecked = createAction(types.STORAGE_CHECKED, data => data);
exports.restorePushCategory = createAction(types.RESTORE_PUSH_CATEGORY, data => data);
exports.fetchPushCategoryList = (data) => (dispath) =>
  Tool.post(Api.pushCategory.query, data, (res) => {
    dispath(getPushCategoryAction(res));
  });

exports.fetchChannelList = (data) => (dispath) =>
  Tool.post(Api.officialChannel.query, data, (res) => {
    dispath(getChannelAction(res));
  });

exports.newChannel = (data, router) => (dispath) =>
  Tool.post(Api.officialChannel.new, data, (res) => {
    if (res.code === 200) {
      dispath(newChannelAction(res));
      router.push('/official/channel');
    } else if (res.code === 90001) {
      dispath(saveMsg(res));
    }
  }, (error) => { console.log('error'); });

exports.getOneChannel = (data, router) => (dispath) =>
  Tool.post(Api.officialChannel.getOne, data, (res) => {
    if (res.code === 200) {
      dispath(getOneChannelAction(res));
      const formData = {
        keyword: '',
        page: 1,
        page_size: 15,
        env: 'online',
        channel_ver: res.data.ver
      };
      Tool.post(Api.pushCategory.query, formData, (result) => {
        dispath(getPushCategoryAction(result));
      });
    } else if (res.code === 90001) {
      console.log('asdfasd');
    }
  }, (error) => { console.log('error'); });

exports.editChannel = (data, router) => (dispath) =>
  Tool.post(Api.officialChannel.edit, data, (res) => {
    if (res.code === 200) {
      router.push('/official/channel');
    } else if (res.code === 90001) {
      dispath(saveMsg(res));
    }
  }, (error) => { console.log('error'); });

exports.pushChannel = (data, router) => (dispath) =>
  Tool.post(Api.officialChannel.push, data, (res) => {
    if (res.code === 200) {
      router.push('/official/channel');
    } else if (res.code === 90001) {
      dispath(saveMsg(res));
    }
  }, (error) => { console.log('error'); });
